<template>
  <div class="container">
    <div class="app-container">
      <!-- 组织架构 -->
      <el-tree :data="depts" :props="defaultProps" :default-expand-all="true" highlight-current="true">
        <template #default="{data}">
          <el-row style="width: 100%;">
            <el-col :span="18">{{ data.name }}</el-col>
            <el-col :span="6">
              <el-row>
                <el-col :span="12">{{ data.managerName ?? '暂无' }}</el-col>
                <el-col :span="12">
                  <!-- 设置一个ElementUI下拉菜单组件 -->
                  <el-dropdown @command="handleCommand($event, data.id)">
                    <span class="el-dropdown-link">
                      操作
                      <i class="el-icon-arrow-down el-icon--right" />
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="add">新增子部门</el-dropdown-item>
                      <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                      <el-dropdown-item command="del">删除</el-dropdown-item>
                    </el-dropdown-menu></el-dropdown></el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-tree>
      <el-tree />
      <!-- 准备一个对话框 -->
      <el-dialog :title="thisType" :visible.sync="showAddDept" @close="handleClose">
        <el-form ref="addForm" label-width="100px" :model="addForm" :rules="rules">
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="addForm.name" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="部门编码" prop="code">
            <el-input v-model="addForm.code" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="部门负责人" prop="managerId">
            <el-select v-model="addForm.managerId" placeholder="请输入">
              <el-option v-for="item in managerList" :key="item.id" :label="item.username" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门介绍" prop="introduce">
            <el-input v-model="addForm.introduce" type="textarea" placeholder="请输入" />
          </el-form-item>
        </el-form>
        <div style="display: flex;justify-content: center;">
          <el-button type="primary" @click="addDept">确定</el-button>
          <el-button @click="showAddDept = false">取消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { addDepartments, deleteDepartment, editDepartment, getDepartDetail, getDepartments, getManagerList } from '@/api/department'
import { transListToTreeData } from '@/utils'

export default {
  name: 'Department',
  data() {
    return {
      list: [],
      thisType: '新增部门',
      parentId: 0,
      depts: [{
        name: '传智教育',
        children: [
          { name: '总裁办' },
          { name: '行政部', children: [{ name: '效率部', children: [{ name: 'DOGE' }] }] },
          { name: '财务部' }
        ]
      },
      {
        name: '易可',
        children: [{ name: '开发部', children: [{ name: '前端开发',
          children: [{ name: 'HarmoneyOS' }, { name: 'Android' }]
        }, { name: '后端开发' }] }, { name: '设计部', children: [{ name: 'UI' }, { name: 'UE' }] }]
      }],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      showAddDept: false,
      form: {
        name: '',
        pid: ''
      },
      addForm: {
        name: '',
        code: '',
        managerId: '',
        introduce: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { validator: (rule, value, callback) => {
            let list = this.list
            if (this.addForm.id) {
              list = list.filter(item => item.id !== this.addForm.id)
            }
            if (list.some(item => item.name === value)) {
              callback(new Error('部门名称已存在'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
          }

        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          // { min: 2, max: 10, message: '部门编码的长度为2-10个字符', trigger: 'blur' },
          { validator: (rule, value, callback) => {
            let list = this.list
            if (this.addForm.id) {
              list = list.filter(item => item.id !== this.addForm.id)
            }
            if (list.some(item => item.code === value)) {
              callback(new Error('部门编码已存在'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
          }
        ],
        managerId: [
          { required: true, message: '请输入部门负责人', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' }
        ]
      },
      managerList: [
        { id: 1, username: '张三' },
        { id: 2, username: '李四' },
        { id: 3, username: '王五' }
      ]
    }
  },
  computed: {
    title() {
      return this.addForm.id ? '编辑' : '新增'
    }
  },
  created() {
    this.getDepartments()
    this.getManagerList()
  },
  methods: {
    handleClose() {
      this.$refs.addForm.resetFields()
      this.addForm = {
        name: '',
        code: '',
        managerId: '',
        introduce: ''
      }
    },
    getManagerList() {
      // 调用接口获取部门负责人列表
      // 然后赋值给managerList
      getManagerList().then(res => {
        this.managerList = res
      })
    },
    async getDepartments() {
      const res = await getDepartments()
      this.list = res
      // console.log('财务部子部门', this.getChildrenDepart(res, 5))
      // console.log('技术部子部门', this.getChildrenDepart(res, 6))
      // console.log('市场部子部门', this.getChildrenDepart(res, 8))
      // console.log('传智子部门', this.getChildrenDepart(res, 1))
      // this.depts = this.getChildrenDepart(res, 0)
      this.depts = transListToTreeData(res, 0)
    },
    handleCommand(command, id) {
      if (command === 'add') {
        this.thisType = '新增部门'
        this.showAddDept = true
        this.parentId = id
        this.addForm = {}
        console.log('新增', id)
      }

      if (command === 'edit') {
        this.thisType = '编辑部门'
        console.log('编辑')
        this.showAddDept = true
        this.parentId = id
        this.getDepartDetail()
      }

      if (command === 'del') {
        this.thisType = '删除部门'
        // this.showAddDept = true
        this.parentId = id
        // 防误触 二次确认
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteDepartment()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    deleteDepartment() {
      deleteDepartment(this.parentId)
        .then(res => {
          this.$message.success('删除部门成功')
          this.getDepartments()
        })
    },
    addDept() {
      if (this.thisType === '新增部门') {
        this.$refs.addForm.validate(async(valid) => {
          if (valid) {
          // console.log('新增部门', this.addForm)
            await addDepartments({
              ...this.addForm,
              pid: this.parentId
            })
            this.getDepartments()
            this.showAddDept = false
            this.$message.success('新增部门成功')
            this.$refs.addForm.resetFields()
          }
        })
      }
      if (this.thisType === '编辑部门') {
        console.log('编辑')
        this.$refs.addForm.validate(async(valid) => {
          if (valid) {
          // console.log('编辑部门', this.addForm)
            await editDepartment({
              ...this.addForm,
              pid: this.parentId
            })
            const res = await getDepartments()
            this.$message.success('编辑部门成功' + JSON.stringify(res))
            this.handleClose()
            this.getDepartments()
            this.showAddDept = false
          }
        })
      }
      if (this.thisType === '删除部门') {
        console.log('删除')
      }
    },
    async getDepartDetail() {
      const res = await getDepartDetail(this.parentId)
      this.addForm = res
    }
    /**
      功能：获取某个部门的子部门
      参数：
        list：部门列表
        departId：部门id
      返回值：
        子部门列表
    */
    // getChildrenDepart(list, departId) {
    //   const arr = []
    //   list.forEach(item => {
    //     if (item.pid === departId) {
    //       // 递归, 找到子部门 带着子部门的item.id  继续找子部门
    //       item.children = this.getChildrenDepart(list, item.id)
    //       arr.push(item)
    //     }
    //   })
    //   return arr
    // }
  }
}
</script>
